﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace autoupdate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            install();
        }
        Timer timer;
        void install()
        {
            timer = new Timer();
            timer.Interval = 10000;
            timer.Tick += new EventHandler(timer_Tick);
            Timer timer2 = new Timer();
            timer2.Interval = 30 * 60000;
            timer2.Tick += new EventHandler(timer2_Tick);
            bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(BWRun);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BWCompleted);

            string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            if (!Directory.Exists(dir + @"\Unitu")) Directory.CreateDirectory(dir + @"\Unitu");

            try
            {
                if (!File.Exists(dir + @"\Unitu\Unita.exe"))
                {
                    File.Copy(AppDomain.CurrentDomain.BaseDirectory + "Unita.exe", dir + @"\Unitu\Unita.exe", true);
                }
            }
            catch (System.Exception ex) { }

            basedir = dir + @"\Unitu\Unitu.exe";
            basedir2 = dir + @"\Unitu\Unita.exe";
            timer.Start();
            timer2.Start();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }
        BackgroundWorker bw;
        string downloadlink = "";
        string basedir = "";
        string basedir2 = "";
        bool status = false;
        FileStream strLocal;

        void writeRUN()
        {
            setAutoRun("Unitu", basedir);
            setAutoRun("Unita", basedir2);
        }
        public void setAutoRun(string key, string val)
        {
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (!IsStartupItem(key))
                rkApp.SetValue(key, val);
        }
        private bool IsStartupItem(string key)
        {
            RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (rkApp.GetValue(key) == null)
                return false;
            else
                return true;
        }
        void killProcess()
        {
            Process[] ps = Process.GetProcessesByName("Unitu.exe");
            foreach (var item in ps)
            {
                try { item.Kill(); }
                catch (System.Exception ex) { }
            }
            ps = Process.GetProcessesByName("Unitu");
            foreach (var item in ps)
            {
                try { item.Kill(); }
                catch (System.Exception ex) { }
            }
        }
        public void BWRun(object sender, DoWorkEventArgs e)
        {
            try
            {
                killProcess();
                download(downloadlink, basedir);
                writeRUN();
                writeRegitry("VERSION", b);
            }
            catch (System.Exception ex)
            {

            }
        }
        private void BWCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            timer.Interval = (5 * 60) * 60000;
        }
        double b;
        void checkupdate()
        {
            string ver = readRegitry("VERSION");
            if (!string.IsNullOrEmpty(ver))
            {
                string wc_return = null;
                try
                {
                    WebClient wc = new WebClient();
                    byte[] bret = wc.DownloadData("http://dangkhoasoft.com/seo/base/index/update/emp/");
                    wc_return = Encoding.UTF8.GetString(bret);
                    wc_return = string.IsNullOrEmpty(wc_return) ? null : wc_return;
                }
                catch (System.Exception ex) { }
                if (!string.IsNullOrEmpty(wc_return))
                {
                    try
                    {
                        double a = 0;
                        b = 0;
                        double.TryParse(ver, out a);
                        string[] data = wc_return.Split('|');
                        double.TryParse(data[0], out b);
                        downloadlink = data[1];
                        if (b > a || !File.Exists(basedir))
                        {
                            Console.WriteLine("Run");
                            Console.WriteLine(basedir);
                            bw.RunWorkerAsync();
                        }
                    }
                    catch (System.Exception ex)
                    {

                    }
                }
            }
            else
            {
                writeRegitry("VERSION", "0");
                checkupdate();
            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            checkupdate();
        }
        private string subKey = "SOFTWARE\\" + Application.ProductName.ToUpper();
        public string SubKey
        {
            get { return subKey; }
            set { subKey = value; }
        }
        private RegistryKey baseRegistryKey = Registry.CurrentUser;
        public RegistryKey BaseRegistryKey
        {
            get { return baseRegistryKey; }
            set { baseRegistryKey = value; }
        }
        string readRegitry(string KeyName)
        {
            RegistryKey rk = baseRegistryKey;
            RegistryKey sk1 = rk.OpenSubKey(subKey);
            if (sk1 == null) return null;
            else
                try { return (string)sk1.GetValue(KeyName.ToUpper()); }
                catch (Exception e) { return null; }
        }
        bool writeRegitry(string KeyName, object Value)
        {
            try
            {
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.CreateSubKey(subKey);
                sk1.SetValue(KeyName.ToUpper(), Value);
                return true;
            }
            catch (Exception e) { return false; }
        }
        bool deleteRegitry(string KeyName)
        {
            try
            {
                RegistryKey rk = baseRegistryKey;
                RegistryKey sk1 = rk.CreateSubKey(subKey);
                if (sk1 == null) return true;
                else sk1.DeleteValue(KeyName);
                return true;
            }
            catch (Exception e) { return false; }
        }
        void download(string sUrlToDnldFile, string sFileSavePath)
        {
            try
            {
                Uri url = new Uri(sUrlToDnldFile);
                string sFileName = Path.GetFileName(url.LocalPath);
                System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                response.Close();
                WebClient client = new WebClient();
                Stream strRemote = client.OpenRead(url);
                strLocal = new FileStream(sFileSavePath, FileMode.Create, FileAccess.Write, FileShare.None);
                int iByteSize = 0;
                byte[] byteBuffer = new byte[1024];
                while ((iByteSize = strRemote.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                {
                    // write the bytes to the file system at the file path specified
                    strLocal.Write(byteBuffer, 0, iByteSize);
                }
                strRemote.Close();
                strLocal.Close();
                status = true;
            }
            catch (Exception exM) { status = false; }
            bool run = false;

            Process[] ps = Process.GetProcessesByName("Unitu.exe");
            if (ps.Length == 0) run = true;
            if (!run)
                ps = Process.GetProcessesByName("Unitu");
            if (ps.Length == 0) run = true;
            if (run)
            {
                try
                {
                    Process.Start(basedir);
                }
                catch (System.Exception ex) { }
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            bool run = false;
            Process[] ps = Process.GetProcessesByName("Unitu.exe");
            if (ps.Length == 0) run = true;
            if (!run)
                ps = Process.GetProcessesByName("Unitu");
            if (ps.Length == 0) run = true;
            if (run)
            {
                try
                {
                    Process.Start(basedir);
                }
                catch (System.Exception ex) { }
            }
        }

    }
}
